package cn.banyingli.banyinglilib.net;

import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * 实现逻辑
 1、定义用于管理Cookie的接口CookieStore;
 2、定义CookieJarImpl类实现CookieJar接口，然后用CookieStore去接管saveFromResponse、loadForRequest 这两个方法；
 3、定义PersistentCookieStore类实现CookieStore接口，用于管理Cookie；
 4、将PersistentCookieStore对象设置到OkHttpClient中；
 https://www.jianshu.com/p/23b35d403148
 */
public class CookieJarImpl implements CookieJar {

    private CookieStore cookieStore;

    public CookieJarImpl(CookieStore cookieStore) {
        if(cookieStore == null) {
            throw new IllegalArgumentException("cookieStore can not be null.");
        }
        this.cookieStore = cookieStore;
    }

    @Override
    public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        this.cookieStore.add(url, cookies);
    }

    @Override
    public synchronized List<Cookie> loadForRequest(HttpUrl url) {
        return this.cookieStore.get(url);
    }

    public CookieStore getCookieStore() {
        return this.cookieStore;
    }
}

